package com.wontube.smr.bo.pub;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import javax.servlet.AsyncContext;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.wontube.client.extension.utils.StringUtils;
import com.wontube.client.extension.utils.net.URLUtils;
import com.wontube.core.pub.AppEnvironment;


/**
 * @author yuechao
 *
 */
public class ProxyDownloadListener implements Runnable {
	private AsyncContext ac;
	private String url;
	private String filename;

	public ProxyDownloadListener(AsyncContext ac, String filename, String url) {
		this.ac = ac;
		this.filename = filename;
		this.url = url;
	}
	
	/*
	 * @see java.lang.Runnable#run()
	 */
	@Override
	public void run() {
		try {
			this.download();
		} catch (IOException e) {
			// 用户取消
		} finally {
			this.ac.complete();
		}
	}

	private void download() throws IOException {
		HttpServletRequest req = (HttpServletRequest)this.ac.getRequest();
		HttpServletResponse resp = (HttpServletResponse)this.ac.getResponse();

		String header= req.getHeader("user-agent");
		if (header == null) {
			header = "";
		}
		
		header = header.toLowerCase();
		String name = this.filename;
		if (header.indexOf("msie") >= 0) {
			name = URLUtils.encodeURIComponent(name);
		} else {
			name = new String(name.getBytes(AppEnvironment.charsetName), "ISO8859_1");
		}

		resp.addHeader("Content-Disposition", StringUtils.format("attachment; filename=\"{}\"", name));
		resp.setContentType("application/octet-stream");
		
		URL uri = new URL(this.url);
		HttpURLConnection conn = (HttpURLConnection) uri.openConnection();
		conn.setConnectTimeout(20000);
		conn.setReadTimeout(20000);
		conn.setRequestProperty("Connection", "Keep-Alive");

		conn.setRequestProperty("user-agent", header);
		
		String range = req.getHeader("Range");
		if (range != null) {
			conn.setRequestProperty("Range", range);
		}
		conn.connect();
		
		int responseCode = conn.getResponseCode();
		long length = conn.getContentLength();
		// 有些服务器的实现不适合ie的设计
		if (range == null && responseCode == HttpURLConnection.HTTP_PARTIAL) {
			responseCode = HttpURLConnection.HTTP_OK;
		}
		resp.setStatus(responseCode);
		resp.setContentLength((int)length);
		if (responseCode == HttpURLConnection.HTTP_PARTIAL) {
			String contentRange = conn.getHeaderField("Content-Range");
			resp.setHeader("Content-Range", contentRange);
		}
		
		InputStream is = conn.getInputStream();
		ServletOutputStream sos = resp.getOutputStream(); 

		try {
			byte[] buffer = new byte[8192];
			while (true) {
				int len = is.read(buffer, 0, buffer.length);
				if (len <= 0) {
					break;
				}
				
				sos.write(buffer, 0, len);
			}
		} finally {
			is.close();
			sos.close();
			conn.disconnect();
		}
	}
}
